using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;

namespace IStrong.EC.WebApi.Results
{
    /// <summary>
    /// 主程序
    /// </summary>
    public class Program
    {
	     /// <summary>
        /// 加载配置文件
        /// </summary>
        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
          .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "Config"))
          .AddJsonFile("framework.json", optional: false, reloadOnChange: true)
          .AddJsonFile($"framework.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true, reloadOnChange: true)
          .AddJsonFile("app.json", optional: false, reloadOnChange: true)
          .AddJsonFile("db.provider.json")
          .AddEnvironmentVariables()
          .Build();

        /// <summary>
        /// 应用程序入口
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            //添加Serilog日志组件
            Log.Logger = new LoggerConfiguration()
              .ReadFrom.Configuration(Configuration)
              .Enrich.FromLogContext()
              .WriteTo.Console()
              .WriteTo.Debug()
              .CreateLogger();

            try
            {
                Log.Information("Getting the motors running...");

                CreateWebHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        /// <summary>
        /// Initializes a new instance of the Microsoft.AspNetCore.Hosting.WebHostBuilder
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
          WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(builder =>
            {
                builder.AddConfiguration(Configuration);
            })
            .UseStartup<Startup>()
            .UseSerilog();
    }
}
